package com.famnote.randomchat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.StringTokenizer;



import org.jivesoftware.smack.XMPPConnection;

/*
import ncsu.course.android.broadcastchat4.BroadcastChatService;
import ncsu.course.android.broadcastchat4.CreateRoomActivity;
import ncsu.course.android.broadcastchat4.FindRoomActivity;
import ncsu.course.android.broadcastchat4.R;
import ncsu.course.android.broadcastchat4.UserNameActivity;
import ncsu.course.android.broadcastchat4.BroadcastChat.ChatMessageBuilder;
import ncsu.course.android.broadcastchat4.BroadcastChat.ChatMessageChecker;
*/


import com.famnote.randomchat.util.SystemUiHider;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
//import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.provider.PrivacyProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.PrivateDataManager;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferNegotiator;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;

import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.provider.AdHocCommandDataProvider;
//import org.jivesoftware.smackx.provider.BytestreamsProvider;
import org.jivesoftware.smackx.provider.DiscoverInfoProvider;
import org.jivesoftware.smackx.provider.DiscoverItemsProvider;
//import org.jivesoftware.smackx.provider.IBBProviders;
import org.jivesoftware.smackx.provider.StreamInitiationProvider;
import org.json.JSONArray;
import org.json.JSONObject;

///import com.famnote.street.R;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.os.AsyncTask;

import android.provider.MediaStore;

import android.media.ExifInterface;
import android.net.Uri;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class RandomChat extends Activity {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;

	
	private static final int LOAD_IMAGE_GALLERY = 0;
	
	
	// Debugging
    private static final String TAG = "BcastChat";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_READ 	= 1;
    public static final int MESSAGE_WRITE 	= 2;
    public static final int MESSAGE_TOAST 	= 3;
    
    public static final String ROOM_LIST 			= "room_list";
    private static final long FIND_ROOM_TIME_OUT 	= 2000;
    private ArrayList<String> existingRoomList 		= null;
    private static final int RANDOM_WAIT_WIN 		= 500;
    
    // Key names received from the BroadcastChatService Handler
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int INTENT_GET_USERNAME 	= 1;
    private static final int INTENT_CREATE_ROOM 	= 2;
    private static final int INTENT_FIND_ROOM		= 3;

	
    
    //private ArrayList<String> messages = new ArrayList<String>();
    private ArrayList<OneComment> messages = new ArrayList<OneComment>();
    
    private Handler mHandler = new Handler();
    
    private DiscussArrayAdapter mAdapter;
    
    
	// Layout Views
    //private TextView 	mTitle;
    private ListView 	mConversationView;
    private EditText 	mOutEditText;
    private Button 		mSendButton;
    private Button 		mNewButton;

    // Array adapter for the conversation thread
    //private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Member object for the chat services
    //////private BroadcastChatService mChatService = null;
    
    
    // message format
    private static final String CMD 	= "cmd=";
    private static final String ROOM 	= "room=";
    private static final String BODY 	= "body=";
    private static final String CMD_FIND_ROOM 		= "1";
    private static final String CMD_ROOM_NAME_ACK 	= "2";
    private static final String CMD_MESSAGE 		= "3";
    private static final String DELIMITER			= "||";
        
    //user and room name
    private String mUserName;
    private String mRoomName = "room1";
    
    
    
    private SettingsDialog mDialog;
    private XMPPConnection connection;
    
    private String mPartner;
    
    private String mRoom;
    private String mNickName;
    
    private ProgressDialog dialog;
    
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_fullscreen);

		final View controlsView = findViewById(R.id.fullscreen_content_controls);
		//final View contentView = findViewById(R.id.fullscreen_content);
		//final View contentView = findViewById(R.id.list_messages);
		/////mList = (ListView)findViewById(R.id.listMessages);
        ////Log.i("RandomChat", "mList = " + mList);
        /////setListAdapter();
		
		
		
		Bundle b = getIntent().getExtras();
		//mRoom = b.getString("room");
		mNickName = b.getString("nickname");
		
		setTitle(b.getString("title"));
		
		mUserName = "nevertry";
		
		/*
		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
		//mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
		mSystemUiHider = SystemUiHider.getInstance(this, mList, HIDER_FLAGS);
		mSystemUiHider.setup();
		mSystemUiHider
				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
					// Cached values.
					int mControlsHeight;
					int mShortAnimTime;

					@Override
					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
					public void onVisibilityChange(boolean visible) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
							// If the ViewPropertyAnimator API is available
							// (Honeycomb MR2 and later), use it to animate the
							// in-layout UI controls at the bottom of the
							// screen.
							if (mControlsHeight == 0) {
								mControlsHeight = controlsView.getHeight();
							}
							if (mShortAnimTime == 0) {
								mShortAnimTime = getResources().getInteger(
										android.R.integer.config_shortAnimTime);
							}
							controlsView
									.animate()
									.translationY(visible ? 0 : mControlsHeight)
									.setDuration(mShortAnimTime);
						} else {
							// If the ViewPropertyAnimator APIs aren't
							// available, simply show or hide the in-layout UI
							// controls.
							controlsView.setVisibility(visible ? View.VISIBLE
									: View.GONE);
						}

						if (visible && AUTO_HIDE) {
							// Schedule a hide().
							delayedHide(AUTO_HIDE_DELAY_MILLIS);
						}
					}
				});

		*/
		/*
		// Set up the user interaction to manually show or hide the system UI.
		contentView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (TOGGLE_ON_CLICK) {
					mSystemUiHider.toggle();
				} else {
					mSystemUiHider.show();
				}
			}
		});
		*/

		// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.
		//findViewById(R.id.dummy_button).setOnTouchListener(
			//	mDelayHideTouchListener);
		
		
	
		/*
		messages.add("Performing com.famnote.randomchat.Chat activity launch");
    	// Add the incoming message to the list view
    	mHandler.post(new Runnable() {
    		public void run() {
    			setListAdapter();
    		}
    	});
    	*/
		
		
		/*
		mUserName = getResources().getString(R.string.you);
		*/
		/*
		// Dialog for getting the xmpp settings
        mDialog = new SettingsDialog(this);
        
        mHandler.post(new Runnable() {
            public void run() {
                mDialog.show();
            }
        });
        */
		
		
		/*
        // Dialog for getting the xmpp settings
        mDialog = new SettingsDialog(this);

        
        // Set a listener to show the settings dialog
        Button setup = (Button) this.findViewById(R.id.button_new);
        setup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mDialog.show();
                    }
                });
            }
        });
        //setup.setVisibility(View.GONE);
		*/
		

		setupChat();
	}
	
	

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		
		//////////delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	/*
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				d
				elayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};
	*/

	/*
	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};
	*/

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	/*
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}
	
	*/
	
	
	
	
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        //if (connection == null) {
        	//setupChat();
        //}
        

    }
	
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
        /////////if (mChatService != null) mChatService.stop();
        /*
        if (connection != null) {
        	if (mPartner != null) {
    			try {
    				Message msg = new Message(mPartner, Message.Type.chat);
    				msg.setBody("BYE");
    				connection.sendPacket(msg);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
        	}
        	connection.disconnect();
        	connection = null;
        }
        */
        
    }

    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "- ON RESUME -");
        
        //if (connection == null) {
        	//setupChat();
        //}
    }

    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
        //////////if (mChatService != null) mChatService.stop();
        
        //if (connection != null) connection.disconnect();
        /*
        if (connection != null) {
        	
        	if (mPartner != null) {
    			try {
    				Message msg = new Message(mPartner, Message.Type.chat);
    				msg.setBody("BYE");
    				connection.sendPacket(msg);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
        	}
        	
			try {
				Message msg = new Message("mrgonny@push.appaas.com", Message.Type.chat);
				msg.setBody("NOWAIT");
				connection.sendPacket(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
        	connection.disconnect();
        	connection = null;
        	
        }
        */
    }


    public void onDestroy() {
        super.onDestroy();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
        // Stop the Broadcast chat services
        //////////if (mChatService != null) mChatService.stop();
        

        
        if (connection != null) {
        	if (mPartner != null) {
    			try {
    				Message msg = new Message(mPartner, Message.Type.chat);
    				msg.setBody("BYE");
    				connection.sendPacket(msg);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
        	}
        	try {
				Message msg = new Message("mrgonny@push.appaas.com", Message.Type.chat);
				msg.setBody("NOWAIT");
				connection.sendPacket(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	
        	connection.disconnect();
        	connection = null;
        }
        /*
        if (connection != null) {
        	connection.disconnect();
        	connection = null;
        }
        */
    }
	
	
    private void setupChat() {
        //Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        //mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        //mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item);
        mConversationView = (ListView) findViewById(R.id.listView1);
        //mConversationView.setAdapter(mConversationArrayAdapter);

        messages.clear();
        
        /*
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        messages.add(new OneComment(true, "^^"));
        
        messages.add(new OneComment(true, "^^"));
		*/
        
        mAdapter = new DiscussArrayAdapter(this, R.layout.listitem_discuss, messages);
        mConversationView.setAdapter(mAdapter);
        
        /*
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        
        mOutEditText.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					mAdapter.add(new OneComment(false, mOutEditText.getText().toString()));
					////mConversationView.setSelection(mAdapter.getCount() -1);
					
					
					
					try {
		        		
			            if (mPartner != null) {
		            		Message msg = new Message(mPartner, Message.Type.chat);
		            		msg.setBody(mOutEditText.getText().toString());
		            		connection.sendPacket(msg);
		            	}
		        		
			            
			            
					} catch (Exception e) {
						e.printStackTrace();
					}
		        	
					
					mOutEditText.setText("");
					
					
					return true;
				}
				return false;
			}
		});
		*/
        
        
        
        // Initialize the compose field with a listener for the return key
        //mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        
        //mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	if(D) Log.e(TAG, "[sendButton clicked]");
            	
            	/*
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);        
                */
            	
            	mOutEditText = (EditText) findViewById(R.id.edit_text_out);
            	String message = mOutEditText.getText().toString();
            	
            
            	if (message.equals("")) return;
           	

            	/*
            	if (mRoomid != null) {
            		//Chat chat = connection.getChatManager().createChat("room1@")
            		try {
            			String to = mRoomid + "";
	            		Message msg = new Message(to, Message.Type.chat);
	            		msg.setBody(message);
	            		connection.sendPacket(msg);
	            	} catch (Exception e) {
	            		e.printStackTrace();
	            	}
            	}
            	*/
            	
            	/*
            	if (mPartner == null) {
            		String notice = getResources().getString(R.string.no_partner);
            		
            		//mAdapter.add(new OneComment(true, notice));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
            		
            		messages.add(new OneComment(true, notice));
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                			mOutEditText.setText("");
                		}
                	});
            		
            	} else {
            		try {
	            		Message msg = new Message(mPartner, Message.Type.chat);
	            		msg.setBody(message);
	            		connection.sendPacket(msg);
	            	} catch (Exception e) {
	            		e.printStackTrace();
	            	}
	        	
            		//mAdapter.add(new OneComment(false, message));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
            		
            		messages.add(new OneComment(false, message));
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                			mOutEditText.setText("");
                		}
                	});
                	
                	
            	}
            	*/
            	
            	try {
            		Message msg = new Message(mRoom, Message.Type.groupchat);
            		msg.setBody(message);
            		connection.sendPacket(msg);
            	} catch (Exception e) {
            		e.printStackTrace();
            	}
        	
        		//mAdapter.add(new OneComment(false, message));
        		//mConversationView.setSelection(mAdapter.getCount() -1);
        		
            	
        		messages.add(new OneComment(false, "", message));
            	// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			setListAdapter();
            			mOutEditText.setText("");
            		}
            	});
            	
				
				
            	
            }
        });
        
        
        
        mNewButton = (Button) findViewById(R.id.button_new);
        mNewButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	if(D) Log.e(TAG, "[newButton clicked]");
            	
            	
            	
        		if (mPartner != null) {
        			
        			
        			try {
        				Message msg = new Message(mPartner, Message.Type.chat);
        				msg.setBody("BYE");
        				connection.sendPacket(msg);
        			} catch (Exception e) {
        				e.printStackTrace();
        			}
        					
        			mPartner = null;
        			
    				String notice = getResources().getString(R.string.waiting);
            		//mAdapter.add(new OneComment(true, notice));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
    				
    				messages.add(new OneComment(true, "", notice));
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                			mOutEditText.setText("");
                		}
                	});
                	
                	
        			try {
        				Message msg = new Message("mrgonny@push.appaas.com", Message.Type.chat);
        				msg.setBody("WAIT");
        				connection.sendPacket(msg);
	        		
        			} catch (Exception e) {
        				e.printStackTrace();
        			}
                	
                	
        		} else {
        		
    				String notice = getResources().getString(R.string.waiting);
            		//mAdapter.add(new OneComment(true, notice));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
    				
    				messages.add(new OneComment(true, "", notice));
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                		}
                	});
                	
        			try {
        				Message msg = new Message("mrgonny@push.appaas.com", Message.Type.chat);
        				msg.setBody("WAIT");
        				connection.sendPacket(msg);
	        		
        			} catch (Exception e) {
        				e.printStackTrace();
        			}
        		}
	        	
				

            	
            }
        });
        
        
        
        

        /*********************
        // Initialize the BluetoothChatService to perform bluetooth connections
        if(mChatService == null)
        	mChatService = new BroadcastChatService(this, mHandler);
        	*********************/

        // Initialize the buffer for outgoing messages
        if(mOutStringBuffer == null)
        	mOutStringBuffer = new StringBuffer("");
        
        
        
        
        /*
        Thread t = new Thread(new Runnable(){
        	@Override
        	public void run() {
        		
        		// no UI
        		mHandler.post(new Runnable(){
        			@Override
        			public void run() {
        				// UI OK
        				
        				if(D) Log.e(TAG, "++ XMPP connect ++");
        		        
        				ConnectionConfiguration connConfig =
        		        		new ConnectionConfiguration("push.appaas.com", 5222, "push.appaas.com");
        		        connConfig.setSASLAuthenticationEnabled(true);
        		        connConfig.setDebuggerEnabled(true);
        		        
        		        
        		        XMPPConnection connection = new XMPPConnection(connConfig);
        		        

        		        if(D) Log.e(TAG, "++ connection.connect() ++");
        		        
        		        try {
        		            connection.connect();
        		            
        		            if(D) Log.e(TAG, "++ after connection.connect() ++");
        		            
        		            
        		            
        		            connection.loginAnonymously();
        		            //Log.i("XMPPClient", "Logged in as " + connection.getUser());
        		            if(D) Log.e(TAG, "++ connection.loginAnonymously() ++");
        		            
        		            setConnection(connection);
        		            
        		        } catch (XMPPException ex) {
        		            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
        		            Log.e("XMPPClient", ex.toString());
        		            
        		            setConnection(null);
        		        }
        				

        			}
        		});
        	}
        	
        });
        
        t.start();
        */
        
        String msg = getResources().getString(R.string.connecting_to_server);
        dialog = ProgressDialog.show(this, "", msg, true);
        
        new processXmppTask().execute("a", "b", "c");
        
        //setConnection(connection);
                
    }
	
    /*
    private class processXmppTask extends AsyncTask<void, void, void> {
    	
    	@Override
    	protected void doInBackground(void... parmams) {
    		
    	}
    }
    */
    
    private class processXmppTask extends AsyncTask<String, Integer, Long> {
    	
    	@Override
    	protected Long doInBackground(String... urls) {

    		
    		
    		long totalSize = 0;
            
            
    		if(D) Log.e(TAG, "++ XMPP connect ++");
	        
			ConnectionConfiguration connConfig =
	        		new ConnectionConfiguration("push.appaas.com", 5222, "push.appaas.com");
	        //connConfig.setSASLAuthenticationEnabled(true);
	        //connConfig.setDebuggerEnabled(true);
	        
	        
	        XMPPConnection connection = new XMPPConnection(connConfig);
	        

	        if(D) Log.e(TAG, "++ connection.connect() ++");
	        
	        try {
	            connection.connect();
	            
	            if(D) Log.e(TAG, "++ after connection.connect() ++");

	            connection.loginAnonymously();
	            
	            //connection.login("creath", "1234");
	            
	            //Log.i("XMPPClient", "Logged in as " + connection.getUser());
	            if(D) Log.e(TAG, "++ connection.loginAnonymously() ++");
	            
	            
	            ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
	            if (sdm == null) sdm = new ServiceDiscoveryManager(connection);    
	            sdm.addFeature("http://jabber.org/protocol/disco#info");
	            sdm.addFeature("jabber:iq:privacy");
	            
	            configure();
	            
	            /*
	            Collection<HostedRoom> rooms = MultiUserChat.getHostedRooms(connection, "conference.push.appaas.com");
	            for (HostedRoom room : rooms) {
	            	if(D) Log.e(TAG, room.getName());
	            }
	            */
	            
	            /*
	        	if (mRoomid != null) {
	                String room = mRoomid + "@conference.push.appaas.com";
	                MultiUserChat muc = new MultiUserChat(connection, room);
	                muc.join(connection.getUser());
	               
	        	}
	        	*/
	            String roomid = StringUtils.parseName(connection.getUser());
	            mRoom = roomid + "@conference.push.appaas.com";
	            
	            // Create a MultiUserChat using a Connection for a room
                MultiUserChat muc = new MultiUserChat(connection, mRoom);
                // Create the room
                muc.join(mUserName);
                
                // Send an empty room configuration form which indicates that we want an instant room
	            muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
                
                
	            setConnection(connection);
                
                //JabberMUCMessageListener listner = new JabberMUCMessageListener(muc);
            	//connection.addPacketListener(listner, null);
                
	            
	        } catch (XMPPException ex) {
	            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
	            Log.e("XMPPClient", ex.toString());
	            
	            setConnection(null);
	        }
	        
    		dialog.dismiss();
	        
    		return totalSize;
    	}
    	
    	/*
    	@Override
        protected void onPostExecute(String result) {
    		
    		dialog.dismiss();
    	}
    	*/
    	
    }
    
    
    
    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendMessage(String message) {
    	
    	if(mUserName == null){
    		Toast.makeText(this, "Please decide user name first", Toast.LENGTH_SHORT).show();
    		return;
    	}
    	
    	if(mRoomName == null){
    		Toast.makeText(this, "Please decide room first", Toast.LENGTH_SHORT).show();
    		return;
    	}    	
    	 
        // Check that there's actually something to send
        if (message.length() > 0 ) {
        	
        	//message = mUserName +": "+ message ; 
        	
        	
        	
        	try {
        		
	            if (mPartner != null) {
            		Message msg = new Message(mPartner, Message.Type.chat);
            		msg.setBody(message);
            		connection.sendPacket(msg);
            	}
        		
	            /*
				ChatMessageBuilder mb = new ChatMessageBuilder(CMD_MESSAGE, mRoomName, message);
				message = mb.getMessage();
				
				// Get the message bytes and tell the BluetoothChatService to write
	            byte[] send = message.getBytes();
	            mChatService.write(send);
	            // else else else
	            String writeMessage = new String(send);
	            //mConversationArrayAdapter.add(writeMessage);
                */

	            
	            /*
	            ChatMessageChecker mc = new ChatMessageChecker (writeMessage);
                
                if (mc.getCmd().equals( CMD_MESSAGE )) {

                	messages.add(mc.getMessageBody());
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                		}
                	});
                	
                	if (mPartner != null) {
                		Message msg = new Message(mPartner, Message.Type.chat);
                		msg.setBody(mc.getMessageBody());
                		connection.sendPacket(msg);
                	}
                }
	            */
                
                

	            // Reset out string buffer to zero and clear the edit text field
	            mOutStringBuffer.setLength(0);
	            mOutEditText.setText(mOutStringBuffer);
	            
			} catch (Exception e) {
				e.printStackTrace();
			}
        	

        	
        	/*
        	message = mUserName + ": " + message;
        	messages.add(message);
        	// Add the incoming message to the list view
        	mHandler.post(new Runnable() {
        		public void run() {
        			setListAdapter();
        		}
        	});
        	*/
        }
    }
    
    
    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                /////////sendMessage(message);
                
            	mAdapter.add(new OneComment(false, "", message));
            	
            	
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };
    
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
       
        
        if (requestCode == LOAD_IMAGE_GALLERY && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();


            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            if(D) Log.d(TAG, "picturePath " + picturePath);

            /*
            ExifInterface exifMedia;
			try {
                exifMedia = new ExifInterface(picturePath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String exifOrint = exifMedia.getAttribute(ExifInterface.TAG_ORIENTATION);

            int exifOrientation = Integer.parseInt(exifOrint);

            System.out.println("Orientation Tag is:"+exifOrientation);

            System.out.println("Path Of the Image " + picturePath);

            BitmapFactory.Options mOptions=new BitmapFactory.Options();
            mOptions.inSampleSize=2;
            Bitmap imgBitmap = BitmapFactory.decodeFile(picturePath, mOptions);
            Runtime.getRuntime().gc();

            imgBitmap = MyProfileActivity.getResizedBitmapImage(imgBitmap, 60, 60, exifOrientation);
            MessageImageBitmap msgImgBitmap = new MessageImageBitmap();
            msgImgBitmap.setImgBitmap(imgBitmap);
            msgImgBitmap.setImgPath(picturePath);

            MessagePacket packetMsg = new MessagePacket();
            packetMsg.setMsgBitmap(msgImgBitmap);
            packetMsg.setIsSendPacket(true);
            packetMsg.setMessageType(MessagePacket.MESSAGE_TYPE_IMAGE);
            packetMsg.setIMAGE_PATH(picturePath);

            messageWithImage.add(packetMsg);

            customAdapter1.notifyDataSetChanged();
            mList.setSelection(mList.getCount());

            String to = frienduserID;
            dbhHelper.insertMessage(CCMStaticVariable.loginUserId
                    + "@ec202.classicinformatics.com", refineFromjId(to), "",
                    "true", picturePath, 1);

            sendFile(picturePath, frienduserID);
			*/
            
            
            picturePath = "/mnt/sdcard/DCIM/1km/2605567_111265912.jpg";

            
            FileTransferManager manager = new FileTransferManager(connection);
            OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(mPartner);
            File file = new File(picturePath);
            try {
               transfer.sendFile(file, "test_file");
            } catch (XMPPException e) {
               e.printStackTrace();
            }
            
           
            
            while(!transfer.isDone()) {
               if(transfer.getStatus().equals(FileTransfer.Status.error)) {
                  //System.out.println("ERROR!!! " + transfer.getError());
                  if(D) Log.d(TAG, "ERROR!!! " + transfer.getError());
               } else if (transfer.getStatus().equals(FileTransfer.Status.cancelled)
                                || transfer.getStatus().equals(FileTransfer.Status.refused)) {
                  //System.out.println("Cancelled!!! " + transfer.getError());
            	   if(D) Log.d(TAG, "Cancelled!!! " + transfer.getError()); 
               }
               try {
                  Thread.sleep(1000L);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }
            if(transfer.getStatus().equals(FileTransfer.Status.refused) || transfer.getStatus().equals(FileTransfer.Status.error)
             || transfer.getStatus().equals(FileTransfer.Status.cancelled)){
               //System.out.println("refused cancelled error " + transfer.getError());
            	if(D) Log.d(TAG, "refused cancelled error " + transfer.getError());
            } else {
               //System.out.println("Success");
               if(D) Log.d(TAG, "Success");
            }
            
            
            
            
            
            
            
            return;
        }
        
        
        
        
        switch (requestCode) {
       
        
        case INTENT_GET_USERNAME:            
            // When user name input dialog returns
            if (resultCode == Activity.RESULT_OK ) {
            	
            	mUserName = data.getExtras().getString(UserNameActivity.EXTRA_USER_NAME);
            	
            	Toast.makeText(this, "User name changed to "+mUserName, Toast.LENGTH_SHORT).show();
            	
            } else {
                
                Toast.makeText(this, R.string.username_error, Toast.LENGTH_SHORT).show();
            }
            break;
            
            
            
             // when create room dialog returns
        /****************    
        case INTENT_CREATE_ROOM:
        	if (resultCode == Activity.RESULT_OK ) {
            	
        		mRoomName = data.getExtras()
                .getString(CreateRoomActivity.EXTRA_ROOM_NAME);
            	
        		if(mRoomName.indexOf(DELIMITER) != -1){
        			mRoomName = mRoomName.replaceAll(DELIMITER, "!!");
        		}
        		
            	Toast.makeText(this, "Create a room : "+mRoomName, Toast.LENGTH_SHORT).show();
            	mTitle.setText(mRoomName);
            	
            } else {
                
                Toast.makeText(this, R.string.create_room_error, Toast.LENGTH_SHORT).show();
            } 
        	
        	break;
        
        case INTENT_FIND_ROOM:
        	if (resultCode == Activity.RESULT_OK ) {
	        	String mRoomToJoin = data.getExtras()
	            .getString(FindRoomActivity.EXTRA_JOIN_ROOM);
	        	
	        	if(mRoomToJoin != null && mRoomToJoin.length() > 0){
	        		
	        		if(mUserName != null)
	        			sendMessage(">>> "+mUserName +" leave !");
	        		
	        		mRoomName = mRoomToJoin;
	        		mTitle.setText(mRoomName);
	        		
	        		if(mUserName != null)
	        			sendMessage(">>> "+mUserName +" joined !");
	        	}
	        }
        	break;
        	**************************/
            
        }// end switch
    }

    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        
        //inflater.inflate(R.menu.menu, menu);
        
        return true;
    }


    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	
        switch (item.getItemId()) {
        
        
        case R.id.username:
        	/*
            // Launch the UserNameActivity to see devices and do scan
            Intent userNameIntent = new Intent(this, UserNameActivity.class);
            startActivityForResult(userNameIntent, INTENT_GET_USERNAME); 
            */
        	
        	/*
        	Intent takePic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(takePic, LOAD_IMAGE_GALLERY);
            */
        	
        	

        	String picturePath = "/mnt/sdcard/DCIM/1km/2605567_111265912.jpg";

            
            //FileTransferManager manager = new FileTransferManager(connection);
        	
        	ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
            if (sdm == null)
            	sdm = new ServiceDiscoveryManager(connection);
            sdm.addFeature("http://jabber.org/protocol/disco#info");
            sdm.addFeature("jabber:iq:privacy");

            FileTransferNegotiator.setServiceEnabled(connection, true);
            
            
            // Create the file transfer manager
            FileTransferManager manager = new FileTransferManager(connection);

            
            OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer("nevertry@push.appaas.com");
            File file = new File(picturePath);
            try {
               transfer.sendFile(file, "test_file");
            } catch (XMPPException e) {
               e.printStackTrace();
            }
            
           
            
            while (!transfer.isDone()) {
               if(transfer.getStatus().equals(FileTransfer.Status.error)) {
                  //System.out.println("ERROR!!! " + transfer.getError());
                  if(D) Log.d(TAG, "ERROR!!! " + transfer.getError());
               } else if (transfer.getStatus().equals(FileTransfer.Status.cancelled)
                                || transfer.getStatus().equals(FileTransfer.Status.refused)) {
                  //System.out.println("Cancelled!!! " + transfer.getError());
            	   if(D) Log.d(TAG, "Cancelled!!! " + transfer.getError()); 
               }
               try {
                  Thread.sleep(1000L);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }
            if (transfer.getStatus().equals(FileTransfer.Status.refused) || transfer.getStatus().equals(FileTransfer.Status.error)
             || transfer.getStatus().equals(FileTransfer.Status.cancelled)){
               //System.out.println("refused cancelled error " + transfer.getError());
            	if(D) Log.d(TAG, "refused cancelled error " + transfer.getError());
            } else {
               //System.out.println("Success");
               if(D) Log.d(TAG, "Success");
            }
            
            
            return true;
            
        case R.id.createroom:
        	/*
        	// Launch the CreateRoomActivity to see devices and do scan
            Intent createRoomIntent = new Intent(this, CreateRoomActivity.class);
            startActivityForResult(createRoomIntent, INTENT_CREATE_ROOM);
            */
        	return true;
        case R.id.findroom:
        	
        	/*
        	// Launch the CreateRoomActivity to see devices and do scan
        	
        	findRoom();
        	*/
        	return true;
        }

        
        return false;
    }
    
    
    
    /*
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
        	
        	if(D) Log.d(TAG, "[handleMessage !!!!!!!!!!!! ]");
        	
            switch (msg.what) {
            
	            case MESSAGE_WRITE:
	          
					try {
						byte[] writeBuf = (byte[]) msg.obj;
		                // construct a string from the buffer
		                String writeMessage = new String(writeBuf);
		                ChatMessageChecker mc = new ChatMessageChecker (writeMessage);
		                
		                if(mc.getCmd().equals( CMD_MESSAGE ))
		                	mConversationArrayAdapter.add(mc.getMessageBody());
		                
					} catch (Exception e1) {
						e1.printStackTrace();
					} 
	                break;
	            case MESSAGE_READ:
	                String readBuf = (String) msg.obj;
	                
					try {
						
						ChatMessageChecker mc = new ChatMessageChecker(readBuf);
						
						if(mc.getCmd().equals(CMD_FIND_ROOM)){
							
						
							///////sendRoomNameAck();
							
							
						}else if(mc.getCmd().equals(CMD_ROOM_NAME_ACK)){
							
							if(existingRoomList != null){
								if(!existingRoomList.contains(mc.getRoomName()))
									existingRoomList.add(mc.getRoomName());
							}
							
						}else if(mc.getCmd().equals(CMD_MESSAGE)){
							if(mRoomName != null &&  mRoomName.equals(mc.getRoomName())){
								mConversationArrayAdapter.add(mc.getMessageBody());
							}else{
								if(D)Log.d(TAG,"Message from other room : "+mc.getRoomName()+"/"+mc.getMessageBody());
							}
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
					
	                break;               
	            case MESSAGE_TOAST:
	                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
	                               Toast.LENGTH_SHORT).show();
	                break;
            }
        }
    };    
    */
    


    class ChatMessageChecker{
    	String cmd 	= null;
    	String room = null;
    	String body = null;
    	
    	public ChatMessageChecker(String message) throws Exception{
    		
    		StringTokenizer st 	= new StringTokenizer(message,DELIMITER);
    		while(st.hasMoreElements()){
    			String token =  st.nextToken();
    			if(token.startsWith(CMD)){
    				cmd = token.substring(token.indexOf(CMD)+CMD.length());
    				continue;
    			}
    			
    			if(token.startsWith(ROOM)){
    				room = token.substring(token.indexOf(ROOM)+ROOM.length());
    				continue;
    			}
    			if(token.startsWith(BODY)){
    				body = message.substring(message.indexOf(BODY)+BODY.length());
    				continue;
    			}
    		}
    	}
    	
	    private String getRoomName(){
	    	return room;
	    } 
    
	    private String getCmd(){
	    	return cmd;
	    } 
    
	    private String getMessageBody(){
	    	return body;
	    }
    }
    
    
    class ChatMessageBuilder{
    	String message 	= null;
    	
    	public ChatMessageBuilder(String cmd) throws Exception{
    		this(cmd,null,null);
    	}
    	
    	public ChatMessageBuilder(String cmd, String roomName) throws Exception{
    		this(cmd,roomName,null);
    	}
    	
    	public ChatMessageBuilder(String cmd, String room, String body) throws Exception{    
    		if(cmd != null && cmd.equals(CMD_FIND_ROOM)){
    			message = 	CMD + CMD_FIND_ROOM;	
    		}else if (cmd != null && cmd.equals(CMD_ROOM_NAME_ACK) && room !=null){
    			message = 	CMD + CMD_ROOM_NAME_ACK + DELIMITER + ROOM + room;
    		}else if(cmd != null && room != null && body != null){
    			message = CMD + CMD_MESSAGE + DELIMITER + ROOM + room + DELIMITER + BODY +  body;
    		}
    	}
    	
	    private String getMessage(){
	    	return message;
	    }    
    }
    

    
    private void setListAdapter() {
        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item, messages);
        DiscussArrayAdapter adapter = new DiscussArrayAdapter(this, R.layout.listitem_discuss, messages);
        
        mConversationView.setAdapter(adapter);
        
        mConversationView.setSelection(adapter.getCount() -1);
        
        
    }
    
    
    
    
    /**
     * Called by Settings dialog when a connection is establised with the XMPP server
     *
     * @param connection
     */
    public void setConnection(XMPPConnection connection) {
        
    	this.connection = connection;
        
        if (connection != null) {
            
        	

        	
        	// Add a packet listener to get messages sent to us
            //PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
            
            PacketFilter filter = new MessageTypeFilter(Message.Type.groupchat);
        	
          
        	
            //PacketFilter filter = new OrFilter(new MessageTypeFilter(Message.Type.groupchat), 
            	//	new MessageTypeFilter(Message.Type.chat));
         	
        	
            //new OrFilter(new PacketTypeFilter(Message.class), new PacketTypeFilter(Presence.class ))
            
            
            connection.addPacketListener(new PacketListener() {
            	
                public void processPacket(Packet packet) {
                	
                    Message message = (Message) packet;
                    
                    if (message.getBody() != null) {
                        
                    	String fromName = StringUtils.parseResource(message.getFrom());
                    	
                    	//String tt = "CHAT", "Got text [" + message.getBody() + "] from [" + fromName + "]";
                        if(D) Log.e(TAG, fromName);
                        
                        

                        
                        if (fromName.equals(mUserName)) {
                        	
                        } else {
                        	String msgText;

                        	msgText = message.getBody();
                        
                        	messages.add(new OneComment(true, fromName, msgText));
                        	// Add the incoming message to the list view
                        	mHandler.post(new Runnable() {
                        		public void run() {
                        			setListAdapter();
                        		}
                        	});
                        }
                        
                        
                    }
                    
                }
            }, filter);
            
            
            
            
            
            
            
            
            configure();     
              
            
            /*
            ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
            if (sdm == null) sdm = new ServiceDiscoveryManager(connection);    
            sdm.addFeature("http://jabber.org/protocol/disco#info");
            sdm.addFeature("jabber:iq:privacy");
			*/
            
            FileTransferNegotiator.setServiceEnabled(connection, true);
            
            FileTransferManager manager = new FileTransferManager(connection);

            manager.addFileTransferListener(new FileTransferListener() {
               public void fileTransferRequest(final FileTransferRequest request) {
            	   
            	   if(D) Log.e(TAG, "fileTransferRequest");
            	   
                  new Thread(){
                     
                	 @Override
                     public void run() {
                    	 
                        IncomingFileTransfer transfer = request.accept();
                        
                        File mf = Environment.getExternalStorageDirectory();
                        
                        if(D) Log.e(TAG, mf.getAbsoluteFile() + "/DCIM/Camera/" + transfer.getFileName());
                        File file = new File(mf.getAbsoluteFile() + "/DCIM/Camera/" + transfer.getFileName());
                         
                        try{
                        	/*
                        	transfer.recieveFile(file);
                        	
                            String line; 
                            BufferedReader br = new BufferedReader(new FileReader(file)); 
                            while ((line = br.readLine()) != null) {
                            	if(D) Log.e(TAG, line);
                            }
                            */
                            
                            
                            transfer.recieveFile(file);
                            while (!transfer.isDone()) {
                            	
                            	if(D) Log.e(TAG, "receive file...");
                            	
                               try{
                                  Thread.sleep(1000L);
                               }catch (Exception e) {
                                  //Log.e('', e.getMessage());
                               }
                               //if(transfer.getStatus().equals(Status.error)) {
                                  //Log.e('ERROR!!! ', transfer.getError() + '');
                               //}
                               if(transfer.getException() != null) {
                                  transfer.getException().printStackTrace();
                               }
                            }
                            
                            
                         } catch (Exception e) {
                            //Log.e('', e.getMessage());
                        	 if(D) Log.e(TAG, e.getMessage());
                         }
                        
                     };
                     
                   }.start();
                   
                   
                }
             });
            
            
            
            
        }
    }
    
    
    
    class JabberMUCMessageListener implements PacketListener {

        private final MultiUserChat muc;

        public JabberMUCMessageListener(MultiUserChat muc) {
             this.muc = muc;
        }

        @Override
        public void processPacket(Packet p) {
            if (p instanceof Message) {

                final Message msg = (Message) p;

                String jid = muc.getOccupant(msg.getFrom()).getJid(); // returns null

                
                String msgText;

                msgText = msg.getBody();

                //msgText = getResources().getString(R.string.anonymous) + ": " + message.getBody();
                
                messages.add(new OneComment(true, "", msgText));
            	// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			setListAdapter();
            		}
            	});
                
            }
        }
    }
    
    
    
    
    
    //private void configure(ProviderManager pm) {
    private void configure() {
		 
    	ProviderManager pm = ProviderManager.getInstance();
    	
        //  Private Data Storage
        pm.addIQProvider("query","jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());
 
        //  Time
        try {
            pm.addIQProvider("query","jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
        } catch (ClassNotFoundException e) {
            Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time");
        }
 
        /*
        //  Roster Exchange
        pm.addExtensionProvider("x","jabber:x:roster", new RosterExchangeProvider());
 
        //  Message Events
        pm.addExtensionProvider("x","jabber:x:event", new MessageEventProvider());
 
        //  Chat State
        pm.addExtensionProvider("active","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("composing","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("paused","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("inactive","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("gone","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        //  XHTML
        pm.addExtensionProvider("html","http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());
 
        //  Group Chat Invitations
        pm.addExtensionProvider("x","jabber:x:conference", new GroupChatInvitation.Provider());
 
        //  Service Discovery # Items    
        pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
 
        //  Service Discovery # Info
        pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
 
        //  Data Forms
        pm.addExtensionProvider("x","jabber:x:data", new DataFormProvider());
 
        //  MUC User
        pm.addExtensionProvider("x","http://jabber.org/protocol/muc#user", new MUCUserProvider());
 
        //  MUC Admin    
        pm.addIQProvider("query","http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
 
 
        //  MUC Owner    
        pm.addIQProvider("query","http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
 
        //  Delayed Delivery
        pm.addExtensionProvider("x","jabber:x:delay", new DelayInformationProvider());
 
        //  Version
        try {
            pm.addIQProvider("query","jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
        } catch (ClassNotFoundException e) {
            //  Not sure what's happening here.
        }
 
        //  VCard
        pm.addIQProvider("vCard","vcard-temp", new VCardProvider());
 
        //  Offline Message Requests
        pm.addIQProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
 
        //  Offline Message Indicator
        pm.addExtensionProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
 
        //  Last Activity
        pm.addIQProvider("query","jabber:iq:last", new LastActivity.Provider());
 
        //  User Search
        pm.addIQProvider("query","jabber:iq:search", new UserSearch.Provider());
 
        //  SharedGroupsInfo
        pm.addIQProvider("sharedgroup","http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());
 
        //  JEP-33: Extended Stanza Addressing
        pm.addExtensionProvider("addresses","http://jabber.org/protocol/address", new MultipleAddressesProvider());
 		*/
 
       
        //   FileTransfer
        
        pm.addIQProvider("si","http://jabber.org/protocol/si", new StreamInitiationProvider());
 
        
        pm.addIQProvider("query","http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
 
        //pm.addIQProvider("open","http://jabber.org/protocol/ibb", new IBBProviders.Open());
        //pm.addIQProvider("close","http://jabber.org/protocol/ibb", new IBBProviders.Close());
        //pm.addExtensionProvider("data","http://jabber.org/protocol/ibb", new IBBProviders.Data());
 		
        
        pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
        pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());

    
        
        
        //  Privacy
        pm.addIQProvider("query","jabber:iq:privacy", new PrivacyProvider());
 
        pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
        pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError());
        pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError());
        pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError());
        pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError());
        pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError());
    
        /*
        // PubSub
        pm.addIQProvider(
                "query", "http://jabber.org/protocol/disco#items",
                 new org.jivesoftware.smackx.provider.DiscoverItemsProvider()
            );
            
            pm.addIQProvider("query",
                    "http://jabber.org/protocol/disco#info",
                    new org.jivesoftware.smackx.provider.DiscoverInfoProvider());
            
            pm.addIQProvider("pubsub",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.PubSubProvider());

            pm.addExtensionProvider("subscription", PubSubNamespace.BASIC.getXmlns() , new SubscriptionProvider());
            
            pm.addExtensionProvider(
                    "create",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            
            pm.addExtensionProvider("items",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.ItemsProvider());
            
            pm.addExtensionProvider("item",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());
            
            pm.addExtensionProvider("item", "",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());
            
            pm.addExtensionProvider(
                            "subscriptions",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.SubscriptionsProvider());

            pm.addExtensionProvider(
                            "subscriptions",
                            "http://jabber.org/protocol/pubsub#owner",
                            new org.jivesoftware.smackx.pubsub.provider.SubscriptionsProvider());

            pm.addExtensionProvider(
                            "affiliations",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.AffiliationsProvider());
            
            pm.addExtensionProvider(
                            "affiliation",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.AffiliationProvider());
            
            pm.addExtensionProvider("options",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addIQProvider("pubsub",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.PubSubProvider());
            
            pm.addExtensionProvider("configure",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addExtensionProvider("default",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());


            pm.addExtensionProvider("event",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.EventProvider());
            
            pm.addExtensionProvider(
                            "configuration",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.ConfigEventProvider());
            
            pm.addExtensionProvider(
                            "delete",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            
            pm.addExtensionProvider("options",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addExtensionProvider("items",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.ItemsProvider());
            
            pm.addExtensionProvider("item",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());

            pm.addExtensionProvider("headers",
                    "http://jabber.org/protocol/shim",
                    new org.jivesoftware.smackx.provider.HeaderProvider());

            pm.addExtensionProvider("header",
                    "http://jabber.org/protocol/shim",
                    new org.jivesoftware.smackx.provider.HeadersProvider());
            
            
            pm.addExtensionProvider(
                            "retract",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.RetractEventProvider());
            
            pm.addExtensionProvider(
                            "purge",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            

         */


            SmackConfiguration.setKeepAliveInterval(-1);
     
		
	}
    
 
}





